﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Logging;

/// <summary>
///LogicLayer 的摘要说明
/// </summary>
public partial class LogicLayer
{
    #region Construct
    public LogicLayer()
	{
	}
    #endregion

    #region Users
    /// <summary>
    /// 登录
    /// </summary>
    /// <returns>-1 failed 0 success 1 failed </returns>
    public int Logon(string userName, string userPwd, HttpContext context)
    {
        try
        {
            int result = 0;

            //Database db = DatabaseFactory.CreateDatabase();
            Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("connStr");

            string sql = "select count(*) from SYS_User where UserName=@UserName and Password=@UserPwd and Disabled=0";
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@UserName", DbType.String, userName);
            db.AddInParameter(cmd, "@UserPwd", DbType.String, userPwd);

            int n = (int)db.ExecuteScalar(cmd);
            if (n > 0)
                context.Session["CurrentUserName"] = userName;
            else
                result = 1;

            return result;
        }
        catch(Exception ex) {
            //Logger.Write(new LogEntry() { Categories="All", Message=ex.Message, TimeStamp=DateTime.Now, Severity=System.Diagnostics.TraceEventType.Error});
            Logger.Write("LogicLayer.Login:" + ex.Message);
            return -1;
        }
    }

    /// <summary>
    /// 注销
    /// </summary>
    public void Logoff(HttpContext context)
    {
        try
        {
            context.Session.Remove("CurrentUserName");
        }
        catch { }
    }

    /// <summary>
    /// 得到人员的用户名
    /// </summary>
    public string GetUserNameByEmplID(string emplID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select UserName from SYS_UserEmpl where EmplID=@EmplID";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);

            return (string)db.ExecuteScalar(cmd);
        }
        catch (Exception ex)
        {
            Logger.Write("GetUserNameByEmplID:" + ex.Message);
            return string.Empty;
        }
    }
    #endregion

    #region Function

    public bool VerifyFunction(string functionID, string userName)
    {
        try
        {
            if (string.Compare(userName, "admin", true) == 0)
                return true;

            string sql = "select COUNT(*) from SYS_RoleFunction rf ,SYS_RoleUser ru where rf.FunctionID=@FunctionID and ru.UserName=@UserName and rf.RoleID=ru.RoleID";

            Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("connStr");
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@UserName", DbType.String, userName);
            db.AddInParameter(cmd, "@FunctionID", DbType.String, functionID);

            int n = (int)db.ExecuteScalar(cmd);

            if (n > 0)
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            Logger.Write("LogicLayer.VerifyFunction:" + ex.Message);
            return false;
        }
    }
    #endregion

    #region Department
    public List<SYS_Department> ListDeptByParent(string parentID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select * from SYS_Department where ParentID=@ParentID and Disabled=0";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@ParentID", DbType.String, parentID);

            List<SYS_Department> result = new List<SYS_Department>();
            using (IDataReader dataReader = db.ExecuteReader(cmd))
            {
                while (dataReader.Read())
                {
                    SYS_Department obj = GetSYS_DepartmentFromDataReader(dataReader);
                    if (obj != null)
                        result.Add(obj);
                }
            }
            return result;
        }
        catch (Exception ex)
        {
            Logger.Write("ListSYS_Department:" + ex.Message);
            return null;
        }
    }

    public bool HasChildDept(string deptID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select count(*) from SYS_Department where ParentID=@ParentID";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@ParentID", DbType.String, deptID);

            int n = (int)db.ExecuteScalar(cmd);
            if (n > 0)
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            Logger.Write("HasChildDept:" + ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 删除部门，同时删除下属部门，调整部门人员
    /// </summary>
    public bool DelDepartment(string deptID)
    {
        try
        {
            //get child deptid
            string childDeptID = GetChildDeptIDString(deptID, true);

            Database db = DatabaseFactory.CreateDatabase("connStr");

            //disable current dept
            string sql = "update SYS_Department set Disabled=1 where DeptID=@DeptID";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@DeptID", DbType.String, deptID);
            db.ExecuteNonQuery(cmd);
            
            //move current dept users
            cmd.CommandText = "delete SYS_EmplDept where DeptID=@DeptID";
            db.ExecuteNonQuery(cmd);

            //disable child dept
            cmd.CommandText = "update SYS_Department set Disabled=1 where DeptID in ('" + childDeptID.Replace(",","','") + "')";
            cmd.Parameters.Clear();
            db.ExecuteNonQuery(cmd);

            //move child dept users
            cmd.CommandText = "delete SYS_EmplDept where DeptID in ('" + childDeptID.Replace(",", "','") + "')";
            db.ExecuteNonQuery(cmd);

            return true;
        }
        catch (Exception ex)
        {
            Logger.Write("DelDepartment:" + ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 得到子部门的ID字符串
    /// </summary>
    /// <param name="includeSubChild">是否包含下级子部门</param>
    /// <returns>逗号分割，如 0001,0002,0003</returns>
    public string GetChildDeptIDString(string parentID, bool includeSubChild)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select DeptID from SYS_Department where ParentID=@ParentID and Disabled=0";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@ParentID", DbType.String, parentID);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            List<string> idList = new List<string>();
            using (IDataReader dataReader = db.ExecuteReader(cmd))
            {
                while (dataReader.Read())
                {
                    idList.Add(dataReader.GetString(0));
                    sb.Append("," + dataReader.GetString(0));
                }
            }

            if (includeSubChild)
            {
                string temp = string.Empty;
                foreach (string childID in idList)
                {
                    temp = GetChildDeptIDString(childID, includeSubChild);
                    if (!string.IsNullOrEmpty(temp))
                        sb.Append("," + temp);
                }
            }

            string result = sb.ToString();
            if (result.Length > 1)
                result = result.Substring(1);

            return result;
        }
        catch (Exception ex)
        {
            Logger.Write("GetChildDeptIDString:" + ex.Message);
            return string.Empty;
        }
    }

    /// <summary>
    /// 得到人员所在部门的名称
    /// </summary>
    public string GetDeptNameByEmplID(string emplID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select d.DeptName from SYS_EmplDept ed, SYS_Department d where ed.EmplID=@EmplID and ed.DeptID=d.DeptID";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);

            string result = string.Empty;
            using (IDataReader dataReader = db.ExecuteReader(cmd))
            {
                while (dataReader.Read())
                {
                    result += "," + dataReader.GetString(0);
                }
            }
            if (result.IndexOf(",") > 1)
                result = result.Substring(1);

            return result;
        }
        catch (Exception ex)
        {
            Logger.Write("GetDeptNameByEmplID:" + ex.Message);
            return string.Empty;
        }
    }
    #endregion

    #region Employee
    public bool DisableEmployee(string EmplID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "update SYS_Employee set disabled=1 where EmplID=@EmplID";

            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@EmplID", DbType.String, EmplID);

            db.ExecuteNonQuery(cmd);
            return true;
        }
        catch (Exception ex)
        {
            Logger.Write("DisableEmployee:" + ex.Message);
            return false;
        }
    }

    public List<SYS_Employee> ListEmployees()
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select * from SYS_Employee where disabled=0 ";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

            List<SYS_Employee> result = new List<SYS_Employee>();
            using (IDataReader dataReader = db.ExecuteReader(cmd))
            {
                while (dataReader.Read())
                {
                    SYS_Employee obj = GetSYS_EmployeeFromDataReader(dataReader);
                    if (obj != null)
                        result.Add(obj);
                }
            }
            return result;
        }
        catch (Exception ex)
        {
            Logger.Write("ListSYS_Employee:" + ex.Message);
            return null;
        }
    }
    #endregion
}